package io.a.echo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

public class EchoServer {


    private final int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws Exception {
        if (args.length!= 1) {
            System.err.println("Usage: EchoServer <port>");
            System.exit(1);
        }

        int port = Integer.parseInt(args[0]);
        new EchoServer(port).start();
    }

    public void start() throws Exception {

        // 创建EventLoopGroup，用于处理网络事件
        EventLoopGroup group = new NioEventLoopGroup();
        try {

            // 创建ServerBootstrap，用于引导服务器启动
            ServerBootstrap b = new ServerBootstrap();

            b
            .group(group)
            .channel(NioServerSocketChannel.class)
            .localAddress(new InetSocketAddress(port))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    // 将EchoServerHandler添加到ChannelPipeline中
                    ch.pipeline().addLast(new EchoHandler());
                }
            });

            // 绑定服务器，并等待绑定完成
            ChannelFuture future = b.bind().sync();

            // 等待服务器关闭
            future.channel().closeFuture().sync();
        } finally {
            // 关闭EventLoopGroup，释放资源
            group.shutdownGracefully().sync();
        }
    }


}